<?php
class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
		// page action renders "static" pages stored under 'protected/views/site/pages'
		// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
		),
		);
	}

	/**c 
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{

		//layout
		$this->layout = 'home';
		
		if(Yii::app()->request->isAjaxRequest)
		{
			$ii   = Yii::app()->request->getParam('ii',0);
			$list = Rates::getInterRate();
			echo $list[$ii]->LocalRate;
			Yii::app()->end();
		}
		
		$this->render('index');
	}	
	
	

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}
	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		//QT check category
		$model= new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes = $_POST['ContactForm'];
			if($model->validate())
			{
				$mail = $this->configMail();
				$mail->SetFrom($model->email);
				$mail->AddAddress(Yii::app()->params['adminEmail']);
				$mail->Subject = $model->subject;
				
				$model->body = <<<CONTENT
					Name: {$model->name}
					Phone: {$model->phone}
					Email: {$model->email}
					Category: {$model->category},
					Message: {$model->body}
CONTENT;
				$mail->Body = $model->body;
				
				if($mail->Send())
					Yii::app()->user->setFlash('contact-success',Yii::t('site','Thank you for contacting us. We will respond to you as soon as possible.'));
				else
					Yii::app()->user->setFlash('contact-error', Yii::t('site','Mail error!'.$mail->ErrorInfo));

				$this->refresh();
			}
		}

		$this->render('contact',array('model'=>$model));
	}
	
	/**
	 * Config php mailer
	 * @return returnType returnDescription
	 */
	private function configMail() {
		$mail = Yii::app()->mailer;
	    $mail->IsSMTP(); // telling the class to use SMTP
		$mail->Host       = "localhost"; // SMTP server
		$mail->SMTPDebug  = 0;                     // enables SMTP debug information (for testing)
		$mail->SMTPAuth   = true;                  // enable SMTP authentication
		$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
		$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
		$mail->Port       = 465;                   // set the SMTP port for the GMAIL server
		$mail->Username   = CGlobal::$mailUsername;  // GMAIL username
		$mail->Password   = CGlobal::$mailPassword;            // GMAIL password
		
		return $mail;
	}
	
	/**
	 * Show rates phone .
	 *
	 * @return renderView
	 */
	public function actionRates() {
		if(Yii::app()->request->isAjaxRequest)
		{
			$rates = Rates::getInterRate();
			$list  = array();
			$ii    = isset($_REQUEST['ii'])?$_REQUEST['ii']: '';
			$list  = ($ii === ''?$rates: array($rates[$ii]));
			
			//paging
			$this->renderPartial('_counterRates', $this->fetchData($list));
			
			Yii::app()->end();
		}
		
		$list = Rates::getInterRate();
		$this->render('rates', $this->fetchData($list));
		
	}
	
	/**
	 * Dùng để fetch dử liệu cho pagination
	 * @param array $list
	 */
	private function fetchData($list)
	{
		if(count($list) > CGlobal::$ratePageSize )
		{
			$pages = new CPagination(count($list));
			$pages->pageSize = CGlobal::$ratePageSize;
			
			$page = Yii::app()->request->getParam('page',1);
			$list = array_slice($list, ($page-1)*$pages->pageSize, $pages->pageSize);	
			return array('list'=> $list, 'pages' => $pages);		
		}
		else 
		{
			return array('list'=> $list);	
		}
	}

	
	/**
	 * RegisterCustomer
	 *
	 * @return returnType returnDescription
	 */
	public function actionCustomerRegister() {
		
		$model = new TblCustomer();
		
		if(isset($_POST['TblCustomer']))
		{
			$model->attributes=$_POST['TblCustomer'];
			
			if($model->validate())
			{
			
				$phone = trim($model->areacode).trim($model->prefixcode).trim($model->phonenumber);
				
				//add subscriber dùng web service => subscriber_id
				$return = USERDEF::addAniSubscriber($model->firstName, $model->lastName, array($phone));

				if($return->returnStatus == 0 || $return->returnStatus ==1 )
				{
					$model->subscriberID = $return->message; //$return->message contain subscriber_id
					
					//save vào sql server
					try
					{
						if($model->save(false))
						{
							$_identity=new UserIdentity($model->loginID, $model->password);
							$duration=3600*24*30;
							Yii::app()->user->login($_identity, $duration);
							Yii::app()->user->_setUp($model);
						
							$this->redirect($this->createUrl('customer/makePayment', array('lang' => $this->language)));
						}
						else
						{
							throw new CDbException("Save subscriber Fail!");
						}
					}
					catch(CDbException $e)
					{
						
						//save sqlserver fail so you must delete subscriberid on server
						Yii::app()->user->setFlash('custreg-error',$e->getMessage());
						$response = EnticeWS::deleteANISubscriber(trim($model->subscriberID));
						if($response->returnStatus == -1)
						{
							Yii::app()->user->setFlash('custreg-error', 'Rollback is broken. Please delete the subscriber has id is'. $model->subscriberID.' By hand. Thanks!');
							//QT261 send mail to my customer
						}
					}
				}
				else 
				{
					Yii::app()->user->setFlash('custreg-error', 'Save subscriber Fail!');
				}
			}
		}
		
		$this->render('customerRegister', array(
			'model' => $model,
		));
	}

}